<template>
  <el-container class="elheight">
    <el-aside class="appTree">
      <app-tree v-bind:tree-data="treeData" v-on:appTreeClick="treeClickHandle"></app-tree>
    </el-aside>
    <el-main>
      <el-container>
        <el-header class="dzy-main-header">
          <div class="btn-group-el">
            <btn-group :currentSelectedData="currentSelectedData" @btnClickCallback="btnClickCallback"></btn-group>
          </div>
          <div class="dzy-custom-search-box">
            <div>网格层级：
              <el-select v-model="queryData.levelCode" clearable placeholder="请选择">
                <el-option v-for="(item,index) in gridOption" :key="index" :label="item.name" :value="item.code"></el-option>
              </el-select>
            </div>
            <div>网格名称：<el-input placeholder="请输入网格名称" v-model="queryData.name"  clearable class="dzy-custom-input"></el-input></div>
            <div>网格编号：<el-input placeholder="请输入网格编号" v-model="queryData.gridCode" clearable class="dzy-custom-input"></el-input></div>
            <div>网格长姓名：<el-input placeholder="请输入网格长电话" v-model="queryData.gridUserName"  clearable class="dzy-custom-input"></el-input></div>
            <div><el-button @click="searchHandleClick" type="primary" icon="el-icon-search">查询</el-button></div>
          </div>
        </el-header>
        <el-main>
          <app-table
            :page-data="pageData"
            :table-columns="tableColumns"
            v-on:currentChange="handleCurrentChange"
            v-on:handleCheckedRows="handleCheckedRows" />
            <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" :before-close="cancel" :close-on-click-modal="false">
              <el-form :model="formData" :rules="rules" ref="formData" :disabled="showOnly" label-width="120px" size="mini">
                <el-form-item label="名称" prop="name">
                  <el-input v-model="formData.name" placeholder="请输入网格分类名称"></el-input>
                </el-form-item>
                <el-form-item label="上级网格" prop="gridIdArr">
                  <div class="block">
                    <el-cascader
                      placeholder="请选择"
                      :options="treeData"
                      :props="gridIdProps"
                      filterable
                      clearable
                      change-on-select
                      :show-all-levels="false"
                      v-model="formData.gridIdArr"
                      @change="gridChangedEvt">
                    </el-cascader>
                  </div>
                </el-form-item>
                <el-form-item label="网格编号" prop="gridCode">
                  <el-input v-model="formData.gridCode" placeholder="请输入网格编号"></el-input>
                </el-form-item>
                <el-form-item label="网格长">
                  <el-select v-model="formData.leaderUserId" filterable placeholder="请选择网格长" clearable>
                    <el-option v-for="item in allUserData" :key="item.id" :value="item.id" :label="item.name"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="网格户数">
                  <el-input v-model="formData.familyNum" placeholder="请输入网格户数"></el-input>
                </el-form-item>
                <el-form-item label="网格面积(平方米)">
                  <el-input v-model="formData.gridArea" placeholder="请输入网格面积"></el-input>
                </el-form-item>
                <el-form-item label="固定电话">
                  <el-input v-model="formData.telephone" placeholder="请输入固定电话"></el-input>
                </el-form-item>
              </el-form>
              <div v-if="!showOnly" slot="footer" class="dialog-footer">
                <el-button @click="cancel('formData')">取 消</el-button>
                <el-button type="primary" @click="save('formData')" >提 交</el-button>
              </div>
            </el-dialog>
            <el-dialog title="用户配置"
            :visible.sync="dialogFormVisible2"
            :before-close="close">
            <el-form :model="userFormData"
              :rules="rules"
              ref="userFormData"
              :disabled="showOnly"
              label-width="120px"
              size="mini">
              <el-col :span="12">
                <el-form-item label="所属网格" prop="gridName">
                  <el-input v-model="userFormData.gridName" readonly></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="网格编号" prop="gridIdCode">
                  <el-input v-model="userFormData.gridIdCode" readonly></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="用户" prop="userId">
                  <el-select filterable v-model="userFormData.userId" placeholder="请选择用户">
                    <el-option v-for="item in allUserData"
                      :key="item.id"
                      :value="item.id"
                      :label="item.name+':'+item.username"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-form>
            <div v-if="!showOnly" slot="footer" class="dialog-footer">
              <el-button @click="cancel('userFormData')">取 消</el-button>
              <el-button type="primary" @click="saveUser('userFormData')">提 交</el-button>
            </div>
          </el-dialog>
            <el-dialog :visible.sync="showMap" title="划网格" width="70%" top="8vh" :close-on-press-escape="false" :close-on-click-modal="false" :before-close="mapCancel" class="custom-map-dialog">
              <edit-map v-if="showMap" :mode="modeType" @appMapCallback="appMapCallback" :row-id="currentSelectedRowId" :target="mapTarget" ></edit-map>
            </el-dialog>
        </el-main>
      </el-container>
    </el-main>
  </el-container>
</template>

<script>
import CascaderTree from '@/components/CascaderTree'
import AppTree from '@/components/common/AppTree'
import BtnGroup from '@/components/BtnGroup'
import AppTable from '@/components/AppTable'
import EditMap from '@/components/EditMap'
import MapUtil from '@/utils/MapUtil'
import {getLastIdByAllId} from '@/utils/CommonUtil'
import {getDictDataOption} from '@/utils/getDictDataOption'
import {getAllRegion, getAllRegionObj} from '@/utils/region'
import {getUserGridTree, setUserGridTree, setUserRegionTree, getUserRegionTree} from '@/utils/LocalDataUtil'
import {findGrid, findGridTree, createGrid,
  updateGrid, deleteGrid, createMapLocation,
  getUserListDepart, getGridTree, createGridMember,
  updateGridMember, updateMapLocation, getGridMapLocationByGridId} from '@/http/AppApi'
export default {
  data () {
    return {
      tableData: [],
      pageData: {},
      userFormData: {},
      formData: {
        parentId: '',
        name: '',
        gridCode: '',
        leaderUserId: '',
        familyNum: '',
        gridArea: '',
        telephone: ''
      },
      queryData: {},
      allUserData: [],
      treeData: [],
      regionTreeData: [],
      allUserDataArr: [],
      dialogTitle: '',
      currentSelectedRowId: '',
      dialogFormVisible: false,
      dialogFormVisible2: false,
      currentSelectedData: [],
      showOnly: false,
      showMap: false,
      mapTarget: {},
      mapDestory: false,
      modeType: 'full',
      gridMemberType: [{
        label: '网格员',
        value: 1
      },
      {
        label: '网格长',
        value: 0
      }
      ],
      tableColumns: [
        { label: '网格名称', prop: 'name' },
        { label: '网格编号', prop: 'gridCode' },
        { label: '网格长', prop: 'appUserName' },
        { label: '网格长联系方式', prop: 'phone' }
      ],
      rules: {
        gridIdArr: [{
          required: true,
          message: '请选择上级网格',
          trigger: 'blur'
        }],
        name: [{
          required: true,
          message: '请输入网格分类名称',
          trigger: 'blur'
        }],
        gridCode: [{
          required: true,
          message: '请输入网格编号',
          trigger: 'blur'
        }]
      },
      gridIdProps: {
        label: 'name',
        value: 'id'
      },
      gridOption: []
    }
  },
  components: {
    AppTree,
    BtnGroup,
    AppTable,
    EditMap,
    CascaderTree
  },
  mounted () {
    this.getTableData()
    this.getLocalTreeData()
    this.getRetionTreeData()
    this.gridOption = getDictDataOption('网格层级')
  },
  methods: {
    save (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.formData) {
            if (!this.beforeSubmit()) {
              return
            }
            if (this.formData.gridIdArr && this.formData.gridIdArr.length > 0) {
              let len = this.formData.gridIdArr.length - 1
              this.formData.parentId = this.formData.gridIdArr[len]
            }
            if (this.formData.id) {
              updateGrid(this.formData).then(resp => {
                if (resp.code && resp.code === '200') {
                  this.getTableData()
                  this.reloadTreeData()
                  this.dialogFormVisible = false
                  this.$message({
                    showClose: true,
                    message: '修改成功',
                    type: 'success'
                  })
                } else {
                  this.$message({
                    type: 'warning',
                    message: resp.message
                  })
                }
              })
            } else {
              createGrid(this.formData).then(resp => {
                if (resp.code && resp.code === '200') {
                  this.getTableData()
                  this.dialogFormVisible = false
                  this.reloadTreeData()
                  this.$message({
                    showClose: true,
                    message: '新增成功',
                    type: 'success'
                  })
                } else {
                  this.$message({
                    type: 'warning',
                    message: resp.message
                  })
                }
              })
            }
          }
        } else {
          return false
        }
      })
    },
    saveUser (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.userFormData) {
            if (!this.beforeSubmit()) {
              return
            }
            this.$set(this.userFormData, 'memberType', 0)
            if (this.userFormData.id) {
              let d = this.userFormData
              updateGridMember(d).then(resp => {
                if (resp.code && resp.code === '200') {
                  this.getTableData()
                  this.getTreeData()
                  this.cancel(formName)
                  this.$message({
                    type: 'success',
                    message: '修改成功'
                  })
                }
              })
            } else {
              let d = this.userFormData
              createGridMember(d).then(resp => {
                if (resp.code && resp.code === '200') {
                  this.getTableData()
                  this.getTreeData()
                  this.cancel(formName)
                  this.$message({
                    type: 'success',
                    message: '新增成功'
                  })
                }
              })
            }
          }
        } else {
          return false
        }
      })
    },
    del (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          rows.forEach(row => {
            deleteGrid(row).then(resp => {
              if (resp.code && resp.code === '200') {
                this.getTableData()
                this.reloadTreeData()
                this.$message({
                  showClose: true,
                  message: '删除成功',
                  type: 'success'
                })
              } else {
                this.$message({
                  type: 'info',
                  message: resp.message
                })
              }
            })
          })
        })
      }
    },
    cancel (formName) {
      this.mapCancel()
      this.dialogFormVisible = false
      this.dialogFormVisible2 = false
      this.formData = {}
      this.showMap = false
      this.userFormData = {}
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields()
      }
    },
    close (formName) {
      this.mapCancel()
      this.dialogFormVisible = false
      this.formData = {}
      this.userFormData = {}
      this.showMap = false
      this.dialogFormVisible2 = false
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields()
      }
    },
    cancelAsso () {

    },
    getTableData () {
      let param = this.queryData
      findGrid(param).then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data) {
            this.pageData = data
            if (this.pageData.items && this.pageData.items instanceof Array) {
              this.tableData = this.pageData.items
            }
          }
        }
      })
    },
    handleCurrentChange (val) {
      this.queryData.offset = (val - 1) * 10
      this.getTableData()
    },
    getTreeData () {
      getGridTree().then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data) {
            this.treeData = data
          }
        }
      })
    },
    getLocalTreeData () {
      let data = getUserGridTree()
      if (data && data instanceof Array) {
        this.treeData = data
      }
    },
    getRetionTreeData () {
      let regionTreeData = getUserRegionTree()
      if (regionTreeData && regionTreeData instanceof Array) {
        this.regionTreeData = regionTreeData
      }
    },
    reloadTreeData () {
      findGridTree().then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data && data instanceof Array) {
            setUserGridTree(data)
            setUserRegionTree(data)
            this.treeData = data
          }
        }
      })
    },
    beforeSubmit () {
      if (this.formData.allGridId) {
        this.formData.gridId = getLastIdByAllId(this.formData.allGridId)
      }
      return true
    },
    treeClickHandle (data) {
      this.queryData = {}
      this.queryData.likeParentId = data.id
      let gridData = {}
      gridData.id = data.id
      gridData.items = this.treeData
      let gridIdArr = getAllRegion(gridData)
      this.$set(this.formData, 'gridIdArr', gridIdArr)
      this.queryData.offset = 0
      this.getTableData()
    },
    btnClickCallback (callbackData) {
      console.log(callbackData)
      if (callbackData.btnType === 'delete') {
        this.dialogFormVisible = false
        let rows = callbackData.rows
        this.del(rows)
      } else if (callbackData.btnType === 'draw') {
        let rowData = callbackData.rows[0]
        if (rowData) {
          let target = {}
          target.targetId = rowData.id
          target.targetType = 'grid'
          this.mapTarget = target
          this.showMap = true
          this.modeType = 'full'
        }
      } else if (callbackData.btnType === 'check_area') {
        let rowData = callbackData.rows[0]
        if (rowData) {
          let target = {}
          target.targetId = rowData.id
          target.targetType = 'grid'
          this.mapTarget = target
          this.showMap = true
          this.modeType = 'middle'
        }
      } else {
        this.showOnly = callbackData.sohwOnly
        this.dialogTitle = callbackData.dialogTitle
        this.dialogFormVisible = true
        if (callbackData.rows[0]) {
          this.getAllUserData(callbackData.rows[0].id)
        }
        if (callbackData.btnType === 'post') {
          if (this.formData.gridIdArr && this.formData.gridIdArr.length > 0) {
            let arr = this.formData.gridIdArr
            this.formData = {}
            this.$set(this.formData, 'gridIdArr', arr)
            this.gridChangedEvt(arr)
          } else {
            this.formData = {}
          }
        } else if (callbackData.btnType === 'user_config') {
          this.dialogFormVisible = false
          this.dialogFormVisible2 = true
          let data = callbackData.rows[0]
          let regionData = {}
          regionData.id = data.id
          regionData.items = this.treeData
          let temp = getAllRegionObj(regionData)
          this.$set(this.userFormData, 'gridName', temp[temp.length - 1].name)
          this.$set(this.userFormData, 'gridIdCode', temp[temp.length - 1].gridCode)
          this.$set(this.userFormData, 'gridId', data.id)
          if (data.leaderUserId) {
            this.$set(this.userFormData, 'userId', data.leaderUserId)
            this.$set(this.userFormData, 'id', data.gridMemberId)
          }
        } else {
          let obj = JSON.stringify(callbackData.rows[0])
          this.formData = JSON.parse(obj)
          let gridData = {}
          gridData.id = this.formData.parentId
          gridData.items = this.treeData
          let gridIdArr = getAllRegion(gridData)
          this.$set(this.formData, 'gridIdArr', gridIdArr)
        }
      }
    },
    gridChangedEvt (val) {
      if (val instanceof Array && val.length > 0) {
        let len = val.length - 1
        let pid = val[len]
        if (pid === '0') {
          this.$set(this.formData, 'gridCode', '')
          return ''
        }
        let data = {}
        data.isGetGridCode = true
        data.items = this.treeData
        data.id = pid
        let gridCode = getAllRegion(data)
        // 判断网格编号是否是最底层等级
        if (gridCode.substring(gridCode.length - 9) === 'undefined') {
          this.$set(this.formData, 'gridIdArr', '')
          this.$set(this.formData, 'gridCode', '')
          this.$message({showClose: true, message: '不能选择最底层网格！', type: 'error'})
          return
        }
        this.$set(this.formData, 'gridCode', gridCode)
      } else {
        this.$set(this.formData, 'gridCode', '')
      }
    },
    handleCheckedRows (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.currentSelectedData = rows
        this.formData = rows[0]
        this.currentSelectedRowId = rows[0].id
      } else {
        this.currentSelectedData = []
        this.formData = {}
      }
    },
    appMapCallback (appMapInfo) {
      if (appMapInfo.target) {
        let mapLocation = {}
        if (appMapInfo.poly && appMapInfo.poly instanceof Array && appMapInfo.poly.length > 0) {
          let length = appMapInfo.poly.length
          this.saveMapLocationInfoByArray(0, length, appMapInfo)
        } else {
          mapLocation = this.appMapInfo2MapLocation(appMapInfo)
          this.saveMapLocationInfo(mapLocation)
        }
      }
      return ''
    },
    appMapInfo2MapLocation (appMapInfo) {
      let mapLocation = {}
      mapLocation.targetId = appMapInfo.target.targetId
      mapLocation.targetType = appMapInfo.target.targetType
      if (!appMapInfo.poly) {
        mapLocation.mapArea = appMapInfo.polyPathArr
        mapLocation.mapColor = appMapInfo.polyColor
        // 地图信息id存在则不允许修改targetId和targetType
        if (appMapInfo.id) {
          mapLocation.id = appMapInfo.id
          delete mapLocation.targetId
          delete mapLocation.targetType
        }
      }
      if (appMapInfo.clearStatus) {
        mapLocation.clearStatus = appMapInfo.clearStatus
      }
      if (appMapInfo.markPosition) {
        mapLocation.longitude = appMapInfo.markPosition.lng
        mapLocation.latitude = appMapInfo.markPosition.lat
        if (appMapInfo.id) {
          mapLocation.id = appMapInfo.id
        }
      }
      return mapLocation
    },
    saveMapLocationInfoByArray (i, length, appMapInfo) {
      if (i >= length) {
        return
      }
      let mapLocation = {}
      mapLocation = this.appMapInfo2MapLocation(appMapInfo)
      mapLocation.mapArea = appMapInfo.poly[i].polyPathArr
      mapLocation.mapColor = appMapInfo.poly[i].polyColor
      mapLocation.id = appMapInfo.poly[i].id
      if (mapLocation.id) {
        delete mapLocation.targetId
        delete mapLocation.targetType
      }
      i++
      let data = mapLocation
      if (mapLocation.id) {
        updateMapLocation(data).then(resp => {
          if (resp.code && resp.code === '200') {
            if (i === length - 1) {
              this.$message({showClose: true, message: '修改成功', type: 'success'})
              this.showMap = false
            }
            this.saveMapLocationInfoByArray(i, length, appMapInfo)
          }
        })
      } else {
        createMapLocation(data).then(resp => {
          if (resp.code && resp.code === '200') {
            if (i === length - 1) {
              this.$message({showClose: true, message: '保存成功', type: 'success'})
              this.showMap = false
            }
            this.saveMapLocationInfoByArray(i, length, appMapInfo)
          }
        })
      }
    },
    saveMapLocationInfo (mapLocation) {
      if (mapLocation.id) {
        updateMapLocation(mapLocation).then(resp => {
          if (resp.code && resp.code === '200') {
            this.$message({showClose: true, message: '修改成功', type: 'success'})
            this.showMap = false
          }
        })
      } else {
        createMapLocation(mapLocation).then(resp => {
          if (resp.code && resp.code === '200') {
            this.$message({showClose: true, message: '保存成功', type: 'success'})
            this.showMap = false
          }
        })
      }
    },
    mapCancel () {
      this.showMap = false
    },
    searchHandleClick () {
      this.queryData.offset = 0
      this.getTableData()
    },
    getAllUserData (id) {
      getUserListDepart(id).then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data && data instanceof Array) {
            this.allUserData = data
          }
        }
      })
    },
    handelChangeRegion (data) {
      console.log(data)
    },
    baidu2amap (rows) {
      for (let row of rows) {
        getGridMapLocationByGridId(row.id).then(resp => {
          if (resp.code && resp.code === '200') {
            console.log(row.name + ' + [' + row.id + '] 请求成功')
            let mapLocationArr = resp.data
            if (mapLocationArr && mapLocationArr instanceof Array && mapLocationArr.length > 0) {
              for (let map of mapLocationArr) {
                let path = map.mapArea
                console.log(row.name + '老数据: ' + path)
                let id = map.id
                if (path) {
                  let newMap = {id: id}
                  path = path.replace(/@/g, '],[')
                  path = JSON.parse(path)
                  window.AMap.convertFrom(path, 'baidu', function (status, result) {
                    if (result.info === 'ok') {
                      let arr = MapUtil.paths2Array(result.locations)
                      newMap.mapArea = JSON.stringify(arr).toString()
                      console.log(row.name + '新数据: ')
                      console.log(newMap)
                      updateMapLocation(newMap).then(resp => {
                        if (resp.code && resp.code === '200') {
                          console.log(row.name + ' + [' + row.id + '] 修改成功')
                        }
                      })
                    }
                  })
                }
              }
            }
          }
        })
      }
    },
    updateMapInfo () {
      let rows = this.currentSelectedData
      this.baidu2amap(rows)
    }
  },
  computed: {},
  watch: {}
}
</script>
<style scoped>

</style>
